package e.odbo.data.sample.tableid;


import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.I_Session;
import e.odbo.data.bean.key.KeyBuilder;
import e.odbo.data.dao.BaseDAO;
import e.odbo.data.dao.table.I_TableSentenceBuilder;
import e.odbo.data.dao.table.TableDefinition;
import e.odbo.data.dao.table.Field;
import com.openbravo.data.loader.serialize.Datas;
import e.odbo.data.format.Formats;
import com.openbravo.data.loader.serialize.DataWrite;
import com.openbravo.data.loader.serialize.DataRead;


public class TableIdGeneratorDAO extends BaseDAO<TableIdGenerator> {


    public TableIdGeneratorDAO(I_Session s, I_TableSentenceBuilder tableBuilder) {
        super(s, tableBuilder);
    }

    @Override
    public Class getSuportClass() {
        return TableIdGenerator.class;
    }

// tableDefinition table:	table_id_generator 	build time :2019-07-01 07:14:39.410

    @Override
    public TableDefinition getTable() {
        TableDefinition table_id_generatorTableDefinition=new TableDefinition("odbo_table_id_generator" ,new Field[]{
                new Field(TableIdGenerator.ID,Datas.STRING,Formats.STRING),//(PK)
                new Field(TableIdGenerator.NEXT_ID_INT,Datas.INT,Formats.INT),//(notNull)
                new Field(TableIdGenerator.NEXT_ID_LONG,Datas.LONG,Formats.DOUBLE)//(notNull)
        }, new int[] {0}
        );
        return table_id_generatorTableDefinition;
    }

    @Override
    public void writeInsertValues(DataWrite dp,TableIdGenerator obj) throws BasicException {
        dp.setString(1,obj.getId());
        dp.setInteger(2,obj.getNextIdInt());
        dp.setLong(3,obj.getNextIdLong());
    }


    public TableIdGenerator readValues(DataRead dr,TableIdGenerator obj) throws BasicException {
        if(obj==null)
            obj = new TableIdGenerator();
        obj.setId(dr.getString(1));
        obj.setNextIdInt(dr.getInteger(2));
        obj.setNextIdLong(dr.getLong(3));
        return obj;
    }


    public int next_id_int(String tableName)throws BasicException {
        TableIdGenerator generator=find(KeyBuilder.getKey(tableName));
        if(generator==null){
            generator=new TableIdGenerator();
            insert(generator);
        }else{
            generator.nextIdInt++;
            update(generator);
        }
        return generator.nextIdInt;
    }

    public long next_id_long(String tableName)throws BasicException {
        TableIdGenerator generator=find(KeyBuilder.getKey(tableName));
        if(generator==null){
            generator=new TableIdGenerator();
            insert(generator);
        }else{
            generator.nextIdLong++;
            update(generator);
        }
        return generator.nextIdLong;
    }
}
